﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace WSDZ.KM.ZH.PurchaseOrderCollectEntry2
{
    [Description("直接调拨单保存汇总明细信息"), HotUpdate]
    public class DirectAllotBillCollectEntry : AbstractOperationServicePlugIn
    {
        public string logType { get; set; } = "直接调拨单保存汇总明细信息";
        public string btype { get; set; } = "直接调拨单保存汇总明细信息";
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            List<int> IdList = e.DataEntitys.Select(x => x["Id"].ToStringV1().ToInt32V1()).Distinct().Where(y => y != 0).ToList();
            if (IdList == null || IdList.Count < 1)
                return;
            Main(IdList);
        }
        public void Main(List<int> IdList)
        {
            List<PurData> dataList = new List<PurData>();
            int size = 5000;
            int icount = IdList.Count <= size ? 1 : IdList.Count % size > 0 ? IdList.Count / size + 1 : IdList.Count / size;
            for (int i = 0; i < icount; i++)
            {
                List<int> ids = IdList.Skip(i * size).Take(size).ToList();
                string sql = $@"select 
Id=main.FID
,billNo=main.FBILLNO
,entyId=enty.FENTRYID
,unitId=enty.FUNITID --采购单位Id
,matId=mat.FMATERIALID --物料ID
,matNumber=mat.FNUMBER
,qty=enty.FQTY --数量
from T_STK_STKTRANSFERINENTRY enty
inner join T_STK_STKTRANSFERIN main on enty.FID=main.FID
left join T_BD_MATERIAL mat on enty.FSRCMATERIALID=mat.FMATERIALID
where main.FID in ({string.Join(",", ids)})
";
              

                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
                List<PurData> pList = datas.DynamicObjectCollectionToDataList<PurData>();
                dataList.AddRange(pList);
            }
            if (dataList.Count < 1)
                return;
            var dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
            K3HelperV1.Login(Context);
            foreach (var dic in dataDic)
            {
                PurData firstData = dic.Value.FirstOrDefault();
                int seq = 1;
                List<PurData> valuedatas = dic.Value.GroupBy(x => x.matId).Select(x =>
                {
                    PurData fpur = x.FirstOrDefault();
                    fpur.qty = x.Sum(a => a.qty);
                    fpur.seq = seq++;
                    return fpur;
                }).ToList();
                try
                {
                    List<string> sqls = valuedatas.Select(x => $@"/*dialect*/ insert into RLKX_t_Cust_WLHZMX
(FID
,FSeq
,F_RLKX_WLBM  --物料编码
,F_RLKX_JLDW  --计量单位
,F_RLKX_DBSL  --数量
)
values(
{x.Id}
,{x.seq}
,{x.matId}
,{x.unitId}
,{x.qty}
)
").ToList();
                    string sql_del = $@"delete from RLKX_t_Cust_WLHZMX where FID={firstData.Id}";
                    int i=  DBUtils.Execute(Context,sql_del);
                    i= DBUtils.ExecuteBatch(Context,sqls,500);
                  
                }
                catch (Exception ex)
                {
                    LogHelperV1.WSLog(Context, firstData.billNo, "直接调拨单汇总明细保存异常【Direct1002】", ex.Message, false, btype);
                    continue;
                }

            }
            int maxEntyId = DBUtils.ExecuteScalar<int>(Context, $@"select MAX(FEntryID) from RLKX_t_Cust_WLHZMX", 0);
            if (maxEntyId != 0)
            {
                string sql_zz = $@"/*dialect*/ DBCC CHECKIDENT(Z_RLKX_t_Cust_WLHZMX, RESEED,{maxEntyId + 1})";
                DBUtils.Execute(Context, sql_zz);
            }
        }


    }

}
